package com.athl.netty.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @author hl
 * @Data 2020/9/3
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        byte[] content = msg.getContent();
        int len = msg.getLen();
        System.out.println("len = " + len);
        System.out.println("内容 = " + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务器端接收到的消息量=" + (++this.count));
        // 回送uuid
        String uuid = UUID.randomUUID().toString();
        byte[] resContent = uuid.getBytes(CharsetUtil.UTF_8);
        int resLen = resContent.length;
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setContent(resContent);
        messageProtocol.setLen(resLen);
        ctx.writeAndFlush(messageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("server 出现了异常 =" + cause.getMessage());
        ctx.close();
    }
}
